package com.cch.android.imageutil;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;

import com.cch.android.util.MyLog;

public class ImageUtil {
	
	
	/** 
     * 底片效果 
     * @param bmp 
     * @return 
     */  
	public static Bitmap film(Bitmap bmp)  
    {  
        // RGBA的最大值  
        final int MAX_VALUE = 255;  
        int width = bmp.getWidth();  
        int height = bmp.getHeight();  
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
          
        int pixR = 0;  
        int pixG = 0;  
        int pixB = 0;  
          
        int pixColor = 0;  
          
        int newR = 0;  
        int newG = 0;  
        int newB = 0;  
          
        int[] pixels = new int[width * height];  
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);  
        int pos = 0;  
        for (int i = 1, length = height - 1; i < length; i++)  
        {  
            for (int k = 1, len = width - 1; k < len; k++)  
            {  
                pos = i * width + k;  
                pixColor = pixels[pos];  
                  
                pixR = Color.red(pixColor);  
                pixG = Color.green(pixColor);  
                pixB = Color.blue(pixColor);  
                  
                newR = MAX_VALUE - pixR;  
                newG = MAX_VALUE - pixG;  
                newB = MAX_VALUE - pixB;  
                  
                newR = Math.min(MAX_VALUE, Math.max(0, newR));  
                newG = Math.min(MAX_VALUE, Math.max(0, newG));  
                newB = Math.min(MAX_VALUE, Math.max(0, newB));  
                  
                pixels[pos] = Color.argb(MAX_VALUE, newR, newG, newB);  
            }  
        }  
          
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);  
        return bitmap;  
    }  
    /** 
     * 怀旧效果(相对之前做了优化快一倍) 
     * @param bmp 
     * @return 
     */  
    public static Bitmap oldRemeber(Bitmap bmp)  
    {  
        // 速度测试  
        long start = System.currentTimeMillis();  
        int width = bmp.getWidth();  
        int height = bmp.getHeight();  
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
        int pixColor = 0;  
        int pixR = 0;  
        int pixG = 0;  
        int pixB = 0;  
        int newR = 0;  
        int newG = 0;  
        int newB = 0;  
        int[] pixels = new int[width * height];  
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);  
        for (int i = 0; i < height; i++)  
        {  
            for (int k = 0; k < width; k++)  
            {  
                pixColor = pixels[width * i + k];  
                pixR = Color.red(pixColor);  
                pixG = Color.green(pixColor);  
                pixB = Color.blue(pixColor);  
                newR = (int) (0.393 * pixR + 0.769 * pixG + 0.189 * pixB);  
                newG = (int) (0.349 * pixR + 0.686 * pixG + 0.168 * pixB);  
                newB = (int) (0.272 * pixR + 0.534 * pixG + 0.131 * pixB);  
                int newColor = Color.argb(255, newR > 255 ? 255 : newR, newG > 255 ? 255 : newG, newB > 255 ? 255 : newB);  
                pixels[width * i + k] = newColor;  
            }  
        }  
          
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);  
        long end = System.currentTimeMillis();  
        return bitmap;  
    }  
    /** 
     * 黑色条纹效果 
     * @param bmp 
     * @return 
     */  
    public static Bitmap stria(Bitmap bmp)  
    {  
        long start = System.currentTimeMillis();  
          
        int width = bmp.getWidth();  
        int height = bmp.getHeight();  
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); // 创建一个相同大小的图片  
          
        // 保存像素点的RGB值  
        int newR = 0;  
        int newG = 0;  
        int newB = 0;  
          
        int[] pixels = new int[width * height]; // 保存图片的像素点信息  
        bmp.getPixels(pixels, 0, width, 0, 0, width, height); // 将整个图片保存到一维数组中，每width个长度为一行  
          
        final int delta = 40; // 每40个像素的高度作为一个单位  
        final int blackHeight = 10; // 黑色区域高度  
        final int BLACK = 0;  
          
        for (int i = 0; i < height; i++)  
        {  
            // 对图片的进行纵向处理  
            // 每隔30个像素的高度就会产生一个高度为10个像素的黑色宽带  
            // 每40个像素为一个单位，前面的10像素就会被处理成黑色  
            if (i % delta <= blackHeight)  
            {  
                for (int k = 0; k < width; k++)  
                {  
                    // 对当前像素点赋新的RGB值  
                    newR = BLACK;  
                    newG = BLACK;  
                    newB = BLACK;  
                      
                    // Color.argb()，是将四个0~255的值组成一个像素点，也就是RGBA值，A是alpha，即透明度  
                    pixels[i * width + k] = Color.argb(255, newR, newG, newB); // 修改像素点  
                }  
            }  
        }  
          
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height); // 向创建的相同大小的新图片绘像素点值  
        long end = System.currentTimeMillis();  
        return bitmap;  
    }  
    /** 
     * 浮雕效果 
     * @param bmp 
     * @return 
     */  
    public static Bitmap emboss(Bitmap bmp)  
    {  
        int width = bmp.getWidth();  
        int height = bmp.getHeight();  
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
          
        int pixR = 0;  
        int pixG = 0;  
        int pixB = 0;  
          
        int pixColor = 0;  
          
        int newR = 0;  
        int newG = 0;  
        int newB = 0;  
          
        int[] pixels = new int[width * height];  
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);  
        int pos = 0;  
        for (int i = 1, length = height - 1; i < length; i++)  
        {  
            for (int k = 1, len = width - 1; k < len; k++)  
            {  
                pos = i * width + k;  
                pixColor = pixels[pos];  
                  
                pixR = Color.red(pixColor);  
                pixG = Color.green(pixColor);  
                pixB = Color.blue(pixColor);  
                  
                pixColor = pixels[pos + 1];  
                newR = Color.red(pixColor) - pixR + 127;  
                newG = Color.green(pixColor) - pixG + 127;  
                newB = Color.blue(pixColor) - pixB + 127;  
                  
                newR = Math.min(255, Math.max(0, newR));  
                newG = Math.min(255, Math.max(0, newG));  
                newB = Math.min(255, Math.max(0, newB));  
                  
                pixels[pos] = Color.argb(255, newR, newG, newB);  
            }  
        }  
          
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);  
        return bitmap;  
    }  
    /**  
     * 光照效果  
     * @param bmp  
     * @return  
     */  
    public static Bitmap sunshine(Bitmap bmp)  
    {  
        final int width = bmp.getWidth();  
        final int height = bmp.getHeight();  
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
          
        int pixR = 0;  
        int pixG = 0;  
        int pixB = 0;  
          
        int pixColor = 0;  
          
        int newR = 0;  
        int newG = 0;  
        int newB = 0;  
          
        int centerX = width / 2;  
        int centerY = height / 2;  
        int radius = Math.min(centerX, centerY);  
          
        final float strength = 150F; // 光照强度 100~150  
        int[] pixels = new int[width * height];  
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);  
        int pos = 0;  
        for (int i = 1, length = height - 1; i < length; i++)  
        {  
            for (int k = 1, len = width - 1; k < len; k++)  
            {  
                pos = i * width + k;  
                pixColor = pixels[pos];  
                  
                pixR = Color.red(pixColor);  
                pixG = Color.green(pixColor);  
                pixB = Color.blue(pixColor);  
                  
                newR = pixR;  
                newG = pixG;  
                newB = pixB;  
                  
                // 计算当前点到光照中心的距离，平面座标系中求两点之间的距离  
                int distance = (int) (Math.pow((centerY - i), 2) + Math.pow(centerX - k, 2));  
                if (distance < radius * radius)  
                {  
                    // 按照距离大小计算增加的光照值  
                    int result = (int) (strength * (1.0 - Math.sqrt(distance) / radius));  
                    newR = pixR + result;  
                    newG = pixG + result;  
                    newB = pixB + result;  
                }  
                  
                newR = Math.min(255, Math.max(0, newR));  
                newG = Math.min(255, Math.max(0, newG));  
                newB = Math.min(255, Math.max(0, newB));  
                  
                pixels[pos] = Color.argb(255, newR, newG, newB);  
            }  
        }  
          
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);  
        return bitmap;  
    }  
    /** 
     * 图片效果叠加  完全叠加
     * @param bmp 限制了尺寸大小的Bitmap 
     * @return 
     */  
    public static Bitmap overlay(Context mContext,Bitmap bmp,int bmpId)  
    {  
        long start = System.currentTimeMillis();  
        int width = bmp.getWidth();  
        int height = bmp.getHeight();  
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
          
        // 对边框图片进行缩放  
        Bitmap overlay = BitmapFactory.decodeResource(mContext.getResources(), bmpId);  
        int w = overlay.getWidth();  
        int h = overlay.getHeight();  
        float scaleX = width * 1F / w;  
        float scaleY = height * 1F / h;  
        Matrix matrix = new Matrix();  
        matrix.postScale(scaleX, scaleY);  
          
        Bitmap overlayCopy = Bitmap.createBitmap(overlay, 0, 0, w, h, matrix, true);  
          
        int pixColor = 0;  
        int layColor = 0;  
          
        int pixR = 0;  
        int pixG = 0;  
        int pixB = 0;  
        int pixA = 0;  
          
        int newR = 0;  
        int newG = 0;  
        int newB = 0;  
        int newA = 0;  
          
        int layR = 0;  
        int layG = 0;  
        int layB = 0;  
        int layA = 0;  
          
        final float alpha = 0.5F;  
          
        int[] srcPixels = new int[width * height];  
        int[] layPixels = new int[width * height];  
        bmp.getPixels(srcPixels, 0, width, 0, 0, width, height);  
        overlayCopy.getPixels(layPixels, 0, width, 0, 0, width, height);  
          
        int pos = 0;  
        for (int i = 0; i < height; i++)  
        {  
            for (int k = 0; k < width; k++)  
            {  
                pos = i * width + k;  
                pixColor = srcPixels[pos];  
                layColor = layPixels[pos];  
                  
                pixR = Color.red(pixColor);  
                pixG = Color.green(pixColor);  
                pixB = Color.blue(pixColor);  
                pixA = Color.alpha(pixColor);  
                  
                layR = Color.red(layColor);  
                layG = Color.green(layColor);  
                layB = Color.blue(layColor);  
                layA = Color.alpha(layColor);  
                  
                newR = (int) (pixR * alpha + layR * (1 - alpha));  
                newG = (int) (pixG * alpha + layG * (1 - alpha));  
                newB = (int) (pixB * alpha + layB * (1 - alpha));  
                layA = (int) (pixA * alpha + layA * (1 - alpha));  
                  
                newR = Math.min(255, Math.max(0, newR));  
                newG = Math.min(255, Math.max(0, newG));  
                newB = Math.min(255, Math.max(0, newB));  
                newA = Math.min(255, Math.max(0, layA));  
                  
                srcPixels[pos] = Color.argb(newA, newR, newG, newB);  
            }  
        }  
          
        bitmap.setPixels(srcPixels, 0, width, 0, 0, width, height);  
        long end = System.currentTimeMillis();  
        return bitmap;  
    }  
    /** 
     * 图片缩放 
     *  
     * @param bm 
     * @param w 
     *            缩小或放大成的宽 
     * @param h 
     *            缩小或放大成的高 
     * @return 
     */  
    public static Bitmap resizeBitmap(Bitmap bm, float w, float h) {  
        Bitmap BitmapOrg = bm;  
  
        int width = BitmapOrg.getWidth();  
        int height = BitmapOrg.getHeight();  
  
        float scaleWidth =  w / width;  
        float scaleHeight = h / height;  
  
        Matrix matrix = new Matrix();  
        matrix.postScale(scaleWidth, scaleHeight);  
        return Bitmap.createBitmap(BitmapOrg, 0, 0, width, height, matrix, true);  
    }  
    /** 
     * 截取图片的中间的200X200的区域 
     * @param bm 
     * @return 
     */  
    private Bitmap cropCenter(Bitmap bm)  
    {  
        int dstWidth = 200;  
           int dstHeight = 200;  
           int startWidth = (bm.getWidth() - dstWidth)/2;  
           int startHeight = ((bm.getHeight() - dstHeight) / 2);  
           Rect src = new Rect(startWidth, startHeight, startWidth + dstWidth, startHeight + dstHeight);  
           return dividePart(bm, src);  
    }  
      
    /** 
     * 剪切图片 
     * @param bmp 被剪切的图片 
     * @param src 剪切的位置 
     * @return 剪切后的图片 
     */  
    private Bitmap dividePart(Bitmap bmp, Rect src)  
    {  
        int width = src.width();  
        int height = src.height();  
        Rect des = new Rect(0, 0, width, height);  
        Bitmap croppedImage = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
        Canvas canvas = new Canvas(croppedImage);  
        canvas.drawBitmap(bmp, src, des, null);  
        return croppedImage;  
    }  
    /** 
     * 添加边框 
     * @param bm 原图片 
     * @param res 边框资源 
     * @return 
     */  
    public static Bitmap addBigFrame(Context mContext,Bitmap bm, int res)  
    {  
        Bitmap bitmap = decodeBitmap(res,mContext);  
        int width = bm.getWidth();  
        int height = bm.getHeight(); 
        Drawable[] array = new Drawable[2];  
        bm = resizeBitmap(bm, width, height); 
        array[0] = new BitmapDrawable(bm);  
        Bitmap b = resizeBitmap(bitmap, width, height);  
        array[1] = new BitmapDrawable(b);  
        LayerDrawable layer = new LayerDrawable(array);  
        return drawableToBitmap(layer);  
    }  
      
    /** 
     * 将Drawable转换成Bitmap 
     * @param drawable 
     * @return 
     */  
    public static Bitmap drawableToBitmap(Drawable drawable)  
    {  
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);  
        Canvas canvas = new Canvas(bitmap);  
        // canvas.setBitmap(bitmap);  
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());  
        drawable.draw(canvas);  
        return bitmap;  
    }  
      
    /** 
     * 将R.drawable.*转换成Bitmap 
     * @param res 
     * @return 
     */  
    public static Bitmap decodeBitmap(int res,Context mContext)  
    {  
        return BitmapFactory.decodeResource(mContext.getResources(), res);  
    }  
    public static Bitmap scalBitmap(Bitmap bitmapOrg,int newWidth,int newHeight,int rotate){
        //获取这个图片的宽和高   
        int width = bitmapOrg.getWidth();   
        int height = bitmapOrg.getHeight();   
  
        //定义预转换成的图片的宽度和高度   
//        int newWidth = 200;   
//        int newHeight = 200;   
  
        //计算缩放率，新尺寸除原始尺寸   
        float scaleWidth = ((float) newWidth) / width;   
        float scaleHeight = ((float) newHeight) / height;   
  
        // 创建操作图片用的matrix对象   
        Matrix matrix = new Matrix();   
  
        // 缩放图片动作   
        matrix.postScale(scaleWidth, scaleHeight);   
  
        //旋转图片 动作   
        if(rotate!=0)
        matrix.postRotate(rotate);   
  
        // 创建新的图片   
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,   
                          width, height, matrix, true); 
        return resizedBitmap;
    }
    public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}
   public static BitmapFactory.Options setInSampleSize(long lenKb){
	   BitmapFactory.Options opts = new BitmapFactory.Options();
	   opts.inPreferredConfig = Bitmap.Config.RGB_565;   
	    opts.inPurgeable = true;  
	    opts.inInputShareable = true;  
	    
	    if(lenKb>=200)
		    opts.inSampleSize = 2;
	    if(lenKb>=400)
	    	opts.inSampleSize = 4;
	    if(lenKb>=600)
	    	opts.inSampleSize = 6;
	    if(lenKb>=800)
	    	opts.inSampleSize = 8;
	    if(lenKb>=1000)
	    	opts.inSampleSize = 10;
	    return opts;
   }
	//
	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}
	/**\
	 * 
	 * 读取图片压缩
	 * @param filename
	 * @param maxWidth
	 * @param maxHeight
	 * @return
	 */
	public static Bitmap scalePicture(String filename, int maxWidth,int maxHeight) {
	     Bitmap bitmap = null;
	    try {
	BitmapFactory.Options opts = new BitmapFactory.Options();
	                        BitmapFactory.decodeFile(filename, opts);
	                        int srcWidth = opts.outWidth;
	                        int srcHeight = opts.outHeight;
	                        int desWidth = 0;
	                        int desHeight = 0;
	                        // 缩放比例
	                        double ratio = 0.0;
	                        if (srcWidth > srcHeight) {
	                                ratio = srcWidth / maxWidth;
	                                desWidth = maxWidth;
	                                desHeight = (int) (srcHeight / ratio);
	                        } else {
	                                ratio = srcHeight / maxHeight;
	                                desHeight = maxHeight;
	                                desWidth = (int) (srcWidth / ratio);
	                        }
	                        // 设置输出宽度、高度
	                        BitmapFactory.Options newOpts = new BitmapFactory.Options();
	                        newOpts.inSampleSize = (int) (ratio) + 1;
	                        newOpts.inJustDecodeBounds = false;
	                        newOpts.outWidth = desWidth;
	                        newOpts.outHeight = desHeight;
	                        bitmap = BitmapFactory.decodeFile(filename, newOpts);

	                } catch (Exception e) {
	                        // TODO: handle exception
	                }
	                return bitmap;
	        }
	public static Bitmap getScalBima(String uri){
		//对图片进行压缩  
        BitmapFactory.Options options = new BitmapFactory.Options();  
        options.inJustDecodeBounds = true;  
          
        //获取这个图片的宽和高  
        
        Bitmap bitmap = BitmapFactory.decodeFile(uri,options);//此时返回bm为空  
        options.inJustDecodeBounds =false;  
        //计算缩放比  
        int be = (int)(options.outHeight / (float)200);  
        if(be <= 0)  
             be =1;  
        options.inSampleSize =be;  
        //重新读入图片，注意这次要把options.inJustDecodeBounds设为false哦  
        bitmap = BitmapFactory.decodeFile(uri,options);  
        int w = bitmap.getWidth();  
        int h=bitmap.getHeight();  
        return bitmap;
	}
	/**
	 * bitmap转换成byte[]
	 * @param bitmap
	 * @return
	 */
	public static byte[] bitmapToBytes(Bitmap bitmap){
		  if (bitmap == null) {
		     return null;
		  }
		  final ByteArrayOutputStream os = new ByteArrayOutputStream();
		  // 将Bitmap压缩成PNG编码，质量为100%存储
		  bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);//除了PNG还有很多常见格式，如jpeg等。
		  return os.toByteArray();
		 }
	/**
	 * is转换成byte
	 * @param is
	 * @return
	 */
	 public static byte[] streamToBytes(InputStream is) {
	       ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
	       byte[] buffer = new byte[1024];
	       int len;
	       try {
	           while ((len = is.read(buffer)) >= 0) {
	               os.write(buffer, 0, len);
	           }
	       } catch (java.io.IOException e) {
	       }
	       return os.toByteArray();
	 }
	public static long byteToKb(long len){
		long kbLen=0;
		if(len!=0)
			kbLen = len/1024;
		return kbLen;
	}
}
